import JoyrideGuide from '@/pages/components/joyride-guide';
import { SvgIcon } from '@/components/icon';
import { Layout, Flex, Spin, message } from 'antd';
import type { TabsProps } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import useWindowWidth from '@/hooks/event/use-window-width';
import '@/pages/workbench/style/index.css';
import { Tabs } from 'antd';
import AppSearch from '../../../workbench/components/appSearch';
import RightDown from '../../../workbench/components/rightDown';
import WorkbenchAll from '../../../workbench/components/workbenchAll';
import NotData from '@/components/NotData';
import workbenchService from '@/api/services/workbenchService';
import { GetWorkBenhList, MenuContentType } from '@/common';
import fusionService from '@/api/services/fusionService';
import { t } from '@/locales/i18n';
import { CloseOutlined } from '@ant-design/icons';
import FusionBoxInfo from '@/components/box/fusionBoxInfo';
import { useOrchestrationStore } from '@/store/orchestrationStore';
type PositionType = 'left' | 'right';
interface pageType {
  page: number;
  pageSize: number;
  searchText: string;
  appId: string;
  fusionAppId: string;
}

interface PublicAgentProps {
  onChangeCollect?: () => void;
  onGetFusionCollect?: (data: GetWorkBenhList) => void;
  isDeleteCollect?: boolean;
  isSearch?: string | null;
  contentType?: MenuContentType;
}

export default function FusionPublicAgent({
  onChangeCollect,
  onGetFusionCollect,
  isDeleteCollect,
  isSearch = null,
  contentType,
}: PublicAgentProps) {
  const { appName, setShowKeyAgent, fusionAgentSquare } = useOrchestrationStore();
  const { isPc } = useWindowWidth();
  const { Header, Content, Sider } = Layout;
  const [keys, setKeys] = useState('4');
  const [position, setPosition] = useState<PositionType[]>(['left', 'right']);
  const [isNoData, setIsNoData] = useState<boolean>(true); //是否有数据
  const [value, setValue] = useState('');
  const [flag, setflag] = useState<boolean>(false); // 用于防止多次触发
  const [appList, setAppList] = useState([]);
  const [total, setTotal] = useState<number>(0);
  const dataAppId = localStorage.getItem('appId') || '';
  const [defaultPage, setDefaultPage] = useState<pageType>({
    page: 1,
    pageSize: 50,
    searchText: '',
    appId: localStorage.getItem('appId') || '',
    fusionAppId: dataAppId,
  });
  const abortControllerRef = useRef<AbortController | null>(null);
  //获取应用市场列表
  const getPublic = async () => {
    try {
      const abortController = new AbortController();
      const { signal } = abortController;
      // 如果之前有未完成的请求，取消
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
      abortControllerRef.current = abortController;

      const res = await fusionService.getFusionAgentApi(defaultPage, signal);
      setIsNoData(true);
      let data;
      if (defaultPage.page === 1) {
        data = res.app_list;
      } else {
        data = [...appList, ...res.app_list];
      }

      if (!isPc) {
        const uniqueMap = new Map();
        data.forEach((item) => {
          uniqueMap.set(item.app_id, item);
        });
        let uniqueArray = Array.from(uniqueMap.values());
        uniqueArray.sort((a, b) => {
          if (a.isCollect && !b.isCollect) return -1;
          if (!a.isCollect && b.isCollect) return 1;
          return 0;
        });
        setAppList(uniqueArray);
      } else {
        setAppList(data);
      }
      setflag(false);
      setTotal(res.total);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getPublic();
  }, [defaultPage, isDeleteCollect, fusionAgentSquare]);

  useEffect(() => {
    if (isSearch !== null) {
      setDefaultPage((prev) => ({
        ...prev,
        searchText: isSearch,
        page: 1,
      }));
    } else {
      setDefaultPage((prev) => ({
        ...prev,
        searchText: '',
        page: 1,
      }));
    }
  }, [isSearch]);

  // useEffect(() => {
  //   setIsNoData(false);
  // }, [contentType]);

  // 搜索框
  const changeSearchValue = (e: React.ChangeEvent<HTMLInputElement>) => {
    //拿到搜索的数据
    setValue(e.target.value);
    setAppList([]);
    setDefaultPage((prev) => ({
      ...prev,
      searchText: e.target.value,
      page: 1,
    }));
  };
  //取消
  const cancel = () => {
    //拿到搜索的数据
  };

  const operations = (
    <AppSearch isCollect={false} value={value} changeSearchValue={changeSearchValue} />
  );

  const OperationsSlot: Record<PositionType, React.ReactNode> = {
    left: (
      <div className="pl-4 pt-2">
        <SvgIcon icon="ic-logo" style={{ width: 36, height: 36 }} />
      </div>
    ),
    right: <RightDown value={value} changeSearchValue={changeSearchValue} cancel={cancel} />,
  };

  const slot = useMemo(() => {
    if (position.length === 0) {
      return null;
    }
    return position.reduce(
      (acc, direction) => ({ ...acc, [direction]: OperationsSlot[direction] }),
      {},
    );
  }, [position]);

  const onscroll = () => {
    if (appList.length >= total) {
      return;
    }
    setDefaultPage((prev) => ({ ...prev, page: defaultPage.page + 1 }));
  };
  //收藏引用
  const changeCollect = async (item: GetWorkBenhList, e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      if (item.isCollect) {
        await fusionService.deleteCollectAgentApi({ appId: item.app_id, fusionAppId: dataAppId });
        message.success('移除收藏');
      } else {
        await fusionService.collectAgentApi({ appId: item.app_id, fusionAppId: dataAppId });
        message.success('收藏成功');
      }
      setDefaultPage((prev) => ({
        ...prev,
        page: 1,
      }));
      onChangeCollect && onChangeCollect();
    } catch (error) {
      message.error('收藏失败');
    }
  };

  const onChange = (key: string) => {};

  return (
    <>
      <Layout
        className={`m-auto ${
          isPc ? ' mt-2 h-screen   rounded-default' : 'size-full w-full'
        } flex-grow  flex-row`}
      >
        <Layout className="rounded-default">
          <Content style={{ background: '#F3F5F9', padding: 0, borderRadius: '12px' }}>
            {isNoData ? (
              <Header
                style={
                  isPc
                    ? { background: '#F3F5F9', padding: 0, borderRadius: '12px' }
                    : { background: '#F3F5F9', padding: '0' }
                }
              >
                {true ? (
                  <div className={`px-4 pt-2 ${isPc ? 'w-[313px]' : 'w-full'}`}>
                    <div className="flex h-[50px] items-center justify-between ">
                      <div
                        className={`flex items-center rounded-md ${
                          isPc
                            ? 'font-semibold text-@brand-color'
                            : 'text-xl font-font-weight-600 text-text-5'
                        }`}
                      >
                        {isPc && <SvgIcon icon="fusion-agent" size="20" className="mr-1" />}
                        {isPc ? t('sys.menu.fusion.agent') : appName}
                      </div>
                      <div
                        className="cursor-pointer"
                        onClick={() => {
                          setShowKeyAgent(false);
                        }}
                      >
                        <CloseOutlined className="text-base text-[#86909C]" />
                      </div>
                    </div>
                    <div className="pb-3"> {operations}</div>
                    <div className="h-[80vh] overflow-auto [scrollbar-width:none]">
                      {appList.length === 0 ? (
                        <div className="flex   items-center">
                          <NotData iconSize={80} textClassName={'text-sm'} />
                        </div>
                      ) : (
                        <FusionBoxInfo
                          type="fusion"
                          dataList={appList}
                          onScroll={onscroll}
                          changeCollect={changeCollect}
                          flag={flag}
                          setflag={(value) => setflag(value)}
                          isGetFusion={true}
                          onGetFusionCollect={onGetFusionCollect}
                        />
                      )}
                    </div>
                  </div>
                ) : (
                  <div>
                    {appList.length === 0 ? (
                      <div className="flex h-[570px] items-center">
                        <NotData iconSize={80} textClassName={'text-sm'} />
                      </div>
                    ) : (
                      <WorkbenchAll
                        onScroll={onscroll}
                        changeCollect={changeCollect}
                        name={keys}
                        isNoData={isNoData}
                        appList={appList}
                        flag={flag}
                        setflag={(value) => setflag(value)}
                        isGetFusion={true}
                        onGetFusionCollect={onGetFusionCollect}
                      />
                    )}
                  </div>
                )}
              </Header>
            ) : (
              <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
                <Spin size="large" />
              </Flex>
            )}
          </Content>
        </Layout>
      </Layout>
    </>
  );
}
